<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票数据获取工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                    },
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
    <main class="flex-grow container mx-auto px-4 py-8">
        <div class="max-w-md mx-auto bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-semibold mb-4 text-center">股票数据获取</h2>
            
            <div id="status_message" class="hidden mb-4 p-3 rounded text-center"></div>
            
            <div class="space-y-4">
                <div>
                    <label for="stock_code" class="block text-sm font-medium text-gray-700 mb-1">股票代码</label>
                    <input type="text" id="stock_code" value="sh000001" placeholder="例如: sh000001 (上证指数)" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary" required>
                    <p class="mt-1 text-xs text-gray-500">上海股票前加 sh，深圳股票前加 sz</p>
                </div>
                
                <div>
                    <label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">开始日期</label>
                    <input type="date" id="start_date" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary" required>
                </div>
                
                <div>
                    <label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">结束日期</label>
                    <input type="date" id="end_date" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary" required>
                </div>
                
                <button id="download_btn" class="w-full bg-primary text-white py-2 px-4 rounded-md hover:bg-primary/90 transition-colors flex items-center justify-center">
                    <i class="fa fa-download mr-2"></i>
                    <span>下载CSV数据</span>
                </button>
            </div>
            
            <div class="mt-6">
                <h3 class="text-sm font-medium text-gray-700 mb-2">数据来源：东方财富</h3>
            </div>
        </div>
        
        <div class="max-w-2xl mx-auto mt-8">
            <div class="bg-white rounded-lg shadow-md p-4">
                <h3 class="text-sm font-medium text-gray-700 mb-2">数据预览</h3>
                <div class="overflow-x-auto">
                    <table id="data_preview" class="min-w-full text-sm">
                        <thead>
                            <tr class="bg-gray-50 text-left text-xs">
                                <th class="px-2 py-2">日期</th>
                                <th class="px-2 py-2">开盘价</th>
                                <th class="px-2 py-2">最高价</th>
                                <th class="px-2 py-2">最低价</th>
                                <th class="px-2 py-2">收盘价</th>
                                <th class="px-2 py-2">成交量</th>
                            </tr>
                        </thead>
                        <tbody id="preview_body">
                            <tr>
                                <td colspan="6" class="px-4 py-4 text-center text-gray-500 text-sm">选择股票代码和日期范围并点击下载按钮查看数据</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date().toISOString().split('T')[0];
            const oneYearAgo = new Date();
            oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
            const oneYearAgoStr = oneYearAgo.toISOString().split('T')[0];
            
            document.getElementById('start_date').value = oneYearAgoStr;
            document.getElementById('end_date').value = today;
            
            const downloadBtn = document.getElementById('download_btn');
            const statusMessage = document.getElementById('status_message');
            const previewBody = document.getElementById('preview_body');
            
            downloadBtn.addEventListener('click', function() {
                const stockCode = document.getElementById('stock_code').value.trim();
                const startDate = document.getElementById('start_date').value;
                const endDate = document.getElementById('end_date').value;
                
                if (!stockCode) {
                    showStatus('请输入股票代码', 'error');
                    return;
                }
                
                if (!startDate || !endDate) {
                    showStatus('请选择完整的日期范围', 'error');
                    return;
                }
                
                if (new Date(startDate) > new Date(endDate)) {
                    showStatus('开始日期不能晚于结束日期', 'error');
                    return;
                }
                
                showStatus('正在获取数据，请稍候...', 'info');
                downloadBtn.disabled = true;
                downloadBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i><span>处理中...</span>';
                
                fetch('/get_data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        stock_code: stockCode,
                        start_date: startDate,
                        end_date: endDate,
                        source: 'eastmoney'
                    })
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.error || '数据获取失败');
                        });
                    }
                    
                    const contentType = response.headers.get('content-type');
                    if (contentType && contentType.includes('application/json')) {
                        return response.json().then(data => {
                            throw new Error(data.error || '数据获取失败');
                        });
                    }
                    
                    return response.blob().then(blob => {
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.style.display = 'none';
                        a.href = url;
                        
                        const contentDisposition = response.headers.get('content-disposition');
                        let filename = `${stockCode}_数据.csv`;
                        if (contentDisposition) {
                            const filenameMatch = contentDisposition.match(/filename="(.+)"/);
                            if (filenameMatch && filenameMatch[1]) {
                                filename = filenameMatch[1];
                            }
                        }
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                        
                        setTimeout(() => {
                            window.URL.revokeObjectURL(url);
                            document.body.removeChild(a);
                        }, 100);
                        
                        showStatus('数据下载成功', 'success');
                    });
                })
                .catch(error => {
                    showStatus(error.message, 'error');
                })
                .finally(() => {
                    downloadBtn.disabled = false;
                    downloadBtn.innerHTML = '<i class="fa fa-download mr-2"></i><span>下载CSV数据</span>';
                });
            });
            
            function showStatus(message, type) {
                statusMessage.textContent = message;
                statusMessage.className = 'mb-4 p-3 rounded text-center text-sm transition-all duration-300';
                
                if (type === 'error') {
                    statusMessage.classList.add('bg-red-50', 'text-red-700', 'border', 'border-red-200');
                } else if (type === 'success') {
                    statusMessage.classList.add('bg-green-50', 'text-green-700', 'border', 'border-green-200');
                } else {
                    statusMessage.classList.add('bg-blue-50', 'text-blue-700', 'border', 'border-blue-200');
                }
                
                setTimeout(() => {
                    statusMessage.classList.add('opacity-0');
                    setTimeout(() => {
                        statusMessage.classList.add('hidden');
                        statusMessage.classList.remove('opacity-0');
                    }, 300);
                }, 5000);
            }
        });
    </script>
</body>
</html>